package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Description: TODO
 * @Author Mr.Tang
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        // 1. 非空效验
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常, 统一抛出 ApplicationException(自定义异常)
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 按用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        if (existsUser != null) {
            // 打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        // 3. 新增用户，设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        // 当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        // 写入数据库
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户成功！");
    }


    @Override
    public User selectByUserName(String username) {
        // 非空效验
        if (StringUtil.isEmpty(username)) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }


    @Override
    public User login(String username, String password) {
        // 1. 非空效验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            // 打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 2. 按用户名查询用户信息
        User user = userMapper.selectByUserName(username);
        // 3. 对查询结果做非空效验
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", 用户： " + username);
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 4. 对密码做效验
        if (!MD5Util.md5Salt(password,user.getSalt()).equalsIgnoreCase(user.getPassword())) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 打印日志
        log.info("登录成功，" + "用户：" + username);
        // 登录成功
        return user;
    }


    @Override
    public User selectById(Long id) {
        // 1. 非空效验
        if (id == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 调用DAO查询获取对象
        User user = userMapper.selectByPrimaryKey(id);
        // 返回结果
        return user;
    }


    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString() + "，user id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        // 更新用户帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn("操作失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString() + "，user id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        // 更新用户帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        if (updateUser.getArticleCount() < 0) {
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn("操作失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        // 1. 非空校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2. 校验用户是否存在
        User exitsUser = userMapper.selectByPrimaryKey(user.getId());
        if (exitsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 设置值，后序判断不报错   （下面直接调换顺序的方式更好  !user.getUsername().equals(exitsUser.getUsername())）
//        if (exitsUser.getEmail() == null) {
//            exitsUser.setEmail("");
//        }
//        if (exitsUser.getPhoneNum() == null) {
//            exitsUser.setPhoneNum("");
//        }
//        if (exitsUser.getRemark() == null) {
//            exitsUser.setRemark("");
//        }
        // 3. 定义一个标志位，校验用户的参数
        boolean checkAttr = false;  // false表示没有校验通过

        // 4. 定义一个专门用来更新的对象，防止用户传入的User对象设置了其他的属性
        // 当使用动态SQL进行更新的时候，覆盖了没有经过校验的字段
        User updateUser = new User();
        updateUser.setId(user.getId());

        // 5. 对每一个参数进行校验并赋值
        // 校验 username
        if (!StringUtil.isEmpty(user.getUsername()) && !user.getUsername().equals(exitsUser.getUsername())) {
            // 需要更新用户名(登录名)时，要进行唯一性的校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null) {
                // 用户已存在
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            // 数据库中没用找到相应的用户，表示可以修改用户名
            updateUser.setUsername(user.getUsername());
            // 更新标志位
            checkAttr = true;
        }

        // 校验昵称
        if (!StringUtil.isEmpty(user.getNickname()) && !user.getNickname().equals(exitsUser.getNickname())) {
            // 设置昵称
            updateUser.setNickname(user.getNickname());
            // 更新标志位
            checkAttr = true;
        }

        // 校验性别
        if (user.getGender() != null && exitsUser.getGender() != user.getGender()) {
            // 设置性别
            updateUser.setGender(user.getGender());
            // 合法性校验
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);  // 0女 1男 2保密
            }
            // 更新标志位
            checkAttr = true;
        }

        // 校验email
        if (!StringUtil.isEmpty(user.getEmail()) && !user.getEmail().equals(exitsUser.getEmail())) {
            // 设置email
            updateUser.setEmail(user.getEmail());
            // 更新标志位
            checkAttr = true;
        }

        // 校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(exitsUser.getPhoneNum())) {
            // 设置电话号码
            updateUser.setPhoneNum(user.getPhoneNum());
            // 更新标志位
            checkAttr = true;
        }

        // 校验个人简介
        if (!StringUtil.isEmpty(user.getRemark()) && !user.getRemark().equals(exitsUser.getRemark())) {
            // 设置个人简介
            updateUser.setRemark(user.getRemark());
            // 更新标志位
            checkAttr = true;
        }

        // 判断标志位决定是否更新信息
        if (checkAttr == false) {
            log.warn("无效修改!");
            throw new ApplicationException(AppResult.failed("无效修改!"));
        }
        // 调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn("操作失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        // 非空校验
        if (id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            // 用户不存在
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 校验旧密码是否正确
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());// 对旧密码进行加密，获取密文
        // 与用户当前密码比较
        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

        // 生成一个新盐值
        String salt = UUIDUtil.UUID_32();
        // 生成新密码的密文
        String newEncryptPassword = MD5Util.md5Salt(newPassword, salt);

        // 构造新对象
        User updateUser = new User();
        updateUser.setId(user.getId());     // 用户ID
        updateUser.setSalt(salt);           // 新的盐
        updateUser.setPassword(newEncryptPassword);   // 新密文
        Date date = new Date();
        updateUser.setUpdateTime(date);     // 更新时间

        // 调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn("操作失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }














}
